package service;

import mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import pojo.User;
import utils.SqlSessionFactoryUtils;

public class UserService {
     SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
     public User login(String username,String password){
         SqlSession sqlSession = factory.openSession();
         UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
         User user = userMapper.selectByUsername(username);
         if (user !=null){
             if(password.equals(user.getPassword())){
                    return user;
             }else {
                return null;
             }
         }
         return null;
     }

     public boolean add(String username,String password){
         SqlSession sqlSession = factory.openSession();
         UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
         User user = userMapper.selectByUsername(username);
         if (user!=null){
             return false;
         }
         User newUser = new User(null,username,password);
         int i = userMapper.add(newUser);
         sqlSession.commit();
         sqlSession.close();
         return i>0;
     }

    public boolean checkUsername(String username){
        SqlSession sqlSession = factory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.selectByUsername(username);
        if (user!=null){
            return true;
        }
        sqlSession.close();
        return false;
    }
    public boolean register(String username, String password){
        User user = new User(null, username, password);
        SqlSession sqlSession = factory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int result = mapper.add(user);
        sqlSession.commit();
        sqlSession.close();
        return result == 1;
    }
}
